import { useState, lazy } from 'react'
import { useNavigate } from 'react-router-dom'
/* -------------------------------------------------------- Image -- */
import ImgUser		from '@img/login/user.png'
import ImgPwd		from '@img/login/pwd.png'
import ImgLoginBg		from '@img/login/login_bg.png'
/* -------------------------------------------------------- Sync Component -- */
import { loginSuccess } from '@com/login/login'
import Encrypt from '@com/utils/encrypt'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $fn } = window
/* -------------------------------------------------------- Async Component -- */
const Page = lazy(()=>import('#tp/content/page-content'))
const SubmitForm = $lazy.hook(()=>import('#cpt/form/submit-form'))
const Checkbox 	= lazy(()=>import('@antd/form/checkbox'))
// const ImgCode = lazy(()=>import('#cpt/form-element/img-code'))
/* -------------------------------------------------------- Page Component -- */
export const Component = () => {
	const [ checked, setChecked ] = useState(true)
	const navigate = useNavigate()
	const form = {
		api:'user/login',
		labelWidth:'s4',
		size: 'middle',
		scroll: 0,
		paddingClass:'',
		hasMaskLoading:false,
		// param:{ username:'', password:'' },
		data:[
			{ _label:'账户', r:1, name:'username', valid:false, el:{ imgIcon: ImgUser } },
			{ _label:'密码', r:1, name:'password', valid:false, type:'password', rules:0, el:{ imgIcon: ImgPwd } },
		],
		suffix: <Checkbox value={checked} out label='记住密码' onChange={v=>setChecked(v)} />,
		controls:{
			label:0,
			back:{ hide:1 },
			reset:{ hide:1 },
			ok:{ block:1, label:'登录' },
			item:{
				mt:10,
				label:''
			}
		},
		onOk: ({ data, param }) => {
			// 记住密码
			if(checked){
				const model = JSON.parse(JSON.stringify(param))
				for(var i in model){ model[i] = Encrypt.encode(model[i]) }
				$fn.local('remember',model)
			}else{
				$fn.localRemove('remember')
			}
			loginSuccess({ navigate, data, param })
		},
		onInit: ({ formRef }) => {
			const m = $fn.local('remember')
			if($fn.hasObject(m)){
				for(var i in m){ m[i] = Encrypt.decode(m[i]) }
				setChecked(true)
				formRef.setValue( m )
			}else{
				setChecked(false)
			}
		}
	}
	
	return (
		<Page scroll contentClass='h fv' minWidth='auto' style={{background:`url(${ImgLoginBg}) no-repeat center/cover`}}>
			<section className='fxmc ex'>
				<div className='bcf r10px' style={{width:400, padding: '0 30px 30px'}}>
					<h5 className='tc h60 b f16'>登录</h5>
					<SubmitForm {...form} />
				</div>
			</section>
		</Page>
	)
}

export default Component